from PySide6.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget, QFileDialog
from PySide6.QtCore import QDir, QFile, QIODevice
import os

class FileUploader(QWidget):
    def __init__(self):
        super().__init__()

        # 创建布局和按钮
        layout = QVBoxLayout(self)
        self.upload_button = QPushButton("上传文件", self)
        layout.addWidget(self.upload_button)

        # 连接按钮的点击信号到槽函数
        self.upload_button.clicked.connect(self.upload_file)

    def upload_file(self):
        # 使用QFileDialog打开文件对话框
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self, "选择文件", "",
                                                 "All Files (*);;Text Files (*.txt)", options=options)
        if fileName:
            # 获取目标目录（这里假设是用户的主目录，但你可以根据需要更改）
            target_dir = os.path.dirname(__file__)
            basename = os.path.basename(fileName)
            makePath = os.path.join(target_dir,"receivefile",os.path.splitext(basename)[0])
            os.makedirs(makePath, exist_ok=True)
            target_file = os.path.join(makePath,basename)

            # 使用QFile和QFileDevice进行文件复制
            source_file = QFile(fileName)
            target_file_obj = QFile(target_file)

            if source_file.open(QIODevice.ReadOnly) and target_file_obj.open(QIODevice.WriteOnly):
                data = source_file.readAll()
                target_file_obj.write(data)

            source_file.close()
            target_file_obj.close()

            print(f"文件已上传到 {target_file}")

if __name__ == "__main__":
    app = QApplication([])

    uploader = FileUploader()
    uploader.show()

    app.exec_()